﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;  //Authentication 身份验证
using Microsoft.AspNetCore.Authorization;   //Authorization 授权
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace ZhaoXi_Core_WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]  //这里是标记所有地 都要授权，不用授权的要添加AllowAnonymous特性
    ///授权控制器
    public class AuthorizeController : ControllerBase
    {
        private ILogger<AuthorizeController> _Logger = null;

        public AuthorizeController(ILogger<AuthorizeController> logger)
        {
            this._Logger = logger;
            Console.WriteLine($"授权控制器执行了构造函数，时间{DateTime.Now}");
        }

        [HttpGet]
        [Route("Get")]
        [AllowAnonymous]
        public IActionResult Get()
        {
            return new JsonResult(new
            {
                Data = "这个是OK的，这个Api并没有要求授权！"
            });
        }


        [HttpGet]
        [Route("GetAuthorizeData")]
        //[Authorize] //Microsoft.AspNetCore.Authorization 命名空间一定要是这个，否则无法正常使用 
        //标记这个要求要授权才可以使用
        public IActionResult GetAuthorizeData()
        { 
           //获取jwt的负载里面的声明的信息
          var Name = base.HttpContext.AuthenticateAsync().Result.Principal.Claims.FirstOrDefault(a=>a.Type.Equals("Name"))?.Value;

            Console.WriteLine($"this is Name {Name}"); 
            return new JsonResult(new
            {
                Data = "已授权",
                Type = "GetAuthorizeData" 
                //Claims=Newtonsoft.Json.JsonConvert.SerializeObject(Claims)
            });
        }
    }
}